package com.easychat.controller;

import com.easychat.dto.MessageSendDto;
import com.easychat.dto.SysSettingDto;
import com.easychat.dto.TokenUserInfoDto;
import com.easychat.entity.LoginUser;
import com.easychat.entity.RegisterUser;
import com.easychat.entity.UserInfo;
import com.easychat.enums.ExceptionCodeEnum;
import com.easychat.common.LeaseException;
import com.easychat.common.Result;
import com.easychat.entity.CaptchaVo;
import com.easychat.entity.constants.Constants;
import com.easychat.redis.RedisComponent;
import com.easychat.service.AccountService;
import com.easychat.service.UserInfoService;
import com.easychat.vo.LoginResultVO;
import com.easychat.vo.UserInfoVO;
import com.easychat.websocket.MessageHandler;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 10 2024/10/2
 */
@RestController("accountController")
@RequestMapping("/account")
public class AccountController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AccountService accountService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private MessageHandler messageHandler;

    /**
     * 登录
     * @return
     */
    @GetMapping("/checkCode")
    public CaptchaVo checkCode(){
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(100,42);
        //获取小写验证码
        String code = arithmeticCaptcha.text().toLowerCase();
        String checkCodeKey = Constants.REDIS_KEY_CHECK_CODE + UUID.randomUUID().toString();

        stringRedisTemplate.opsForValue().set(checkCodeKey,code, Constants.REDIS_TIME_1MIN * 3, TimeUnit.MINUTES);
        String checkCodeBase64 = arithmeticCaptcha.toBase64();
        Map<String,String> result = new HashMap<>();
        result.put("checkCode",checkCodeBase64);
        CaptchaVo captchaVo = new CaptchaVo(checkCodeBase64,checkCodeKey);
        return captchaVo;
    }

    @PostMapping("/register")
    public Result register(@RequestBody @Valid RegisterUser registerUser
                           ){
        try {
            if(registerUser.getCheckCode().equals(stringRedisTemplate.opsForValue().get(registerUser.getCheckCodeKey()))){
                accountService.register(registerUser.getEmail(),registerUser.getPassword(),registerUser.getNickName());
            }else {

                throw new LeaseException(ExceptionCodeEnum.YXM_ERROR);
            }
        }finally {
            stringRedisTemplate.delete(registerUser.getCheckCodeKey());
        }
        return Result.ok("注册成功！");
    }
    @GetMapping("/login")
    public Result<UserInfoVO> login(@RequestBody @Valid LoginUser loginUser
                                    ){

        try {
            if(!loginUser.getCheckCode().equals(stringRedisTemplate.opsForValue().get(loginUser.getCheckCodeKey()))){
                throw new LeaseException(ExceptionCodeEnum.YXM_ERROR);
            }
            TokenUserInfoDto tokenUserInfoDto = accountService.login(loginUser.getEmail(), loginUser.getPassword());
            UserInfo userInfo = userInfoService.queryById(tokenUserInfoDto.getUserId());
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(userInfo,userInfoVO);
            userInfoVO.setToken(tokenUserInfoDto.getToken());
            userInfoVO.setAdmin(tokenUserInfoDto.getAdmin());
            return Result.ok(userInfoVO);
        }finally {
            stringRedisTemplate.delete(loginUser.getCheckCodeKey());
        }



    }
    @GetMapping("/getSysSetting")
    public Result<SysSettingDto> getSysSetting(){
        return Result.ok(redisComponent.getSysSetting());
    }
    @GetMapping("test")
    public Result test(){
        MessageSendDto<Object> objectMessageSendDto = new MessageSendDto<>();
        objectMessageSendDto.setMessageContent("测试消息"+System.currentTimeMillis());
        messageHandler.sendMessage(objectMessageSendDto);
        return Result.ok();
    }

}
